package logger;

import java.io.*;
import java.util.*;
import utility.*;

public class Logger 
{
	String LogDir =Input.LogDir;
	String loggerpath;
	Date datetime;
	FileWriter fwrite;
	public StringBuffer Logger = new StringBuffer();
	public Logger() 
	{	
		datetime= new Date();
		Logger.append("\nMessage Recieved at : "+datetime.toString()+"\n");
		
		
	}
	
	public void addLog()
	{
		try
		{
			File dir = new File(LogDir);
			if(dir.exists())
				dir.mkdirs();
			
			MyDate date = new MyDate();
			// create log file with current date
			loggerpath = LogDir+date.getDate()+Input.FILRFORMAT;
			File logfile = new File(loggerpath);
			
			System.out.println("logger::Logger:: addLog():: loggerPath is :"+loggerpath);
			
			if(logfile.exists())
			{
				System.out.println("logger::Logger:: addLog()::Logfile already exists");
				
				fwrite = new FileWriter(logfile,true);
				synchronized (this) 
				{
					datetime = new Date();
					//processLogger.append("\nMessage Sent at : "+datetime.toString()+"\n*****\n");
					fwrite.write(Logger.toString());
					fwrite.close();
				}
			}
			else
			{
				if(logfile.createNewFile())
				{
					System.out.println("logger::Logger:: addLog()::Logfile created");
					fwrite = new FileWriter(logfile,true);
					synchronized (this) 
					{
						datetime = new Date();
						//processLogger.append("\nMessage Sent at : "+datetime.toString()+"\n*****\n");
						fwrite.write(Logger.toString());
						fwrite.close();
					}
				}
				else
				{
					System.out.println("logger::Logger:: addLog():: Sorry, File not created");
				}
			}
		}
		catch(Exception e)
		{
			File dir = new File(LogDir);
			dir.mkdirs();
			System.out.println("logger::Logger:: addLog()::error ");
			e.printStackTrace();
		}
	}
	
	public static void main(String args[])
	{
		Logger log = new Logger();
		log.addLog();
	}
}
